<!--20210304    zaq    创建vue文件-->
<!--20210511    zaq    参考https://blog.csdn.net/weixin_41884808/article/details/110393071进行编写-->
<!--20210526    zaq    尝试用echarts显示日历-->

<template>
<!--日程主页-->
  <div style="width: 100%;padding: 0;margin: 0">
    <el-dialog v-model="showDialog">
      <el-form label-width="90px" style="width: 80%">
        <el-form-item label="日程名称:" >
          <el-input
              type="text"
              placeholder="请输入内容"
              v-model="form.cName"
              maxlength="10"
              show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="类型：">
          <el-radio-group v-model="form.cFlag">
            <el-radio :label="1">全天</el-radio>
            <el-radio :label="2">时间段</el-radio>
            <el-radio :label="3">时刻</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="日期：">
          <el-date-picker
              v-model="form.cDate"
              align="right"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item v-if="form.cFlag!=1" label="时间：">
          <el-time-picker
              arrow-control
              v-model="form.cStart"
              placeholder="任意时间点">
          </el-time-picker>
        </el-form-item>
        <el-form-item v-if="form.cFlag==2" label="   至  ：">
          <el-time-picker
              arrow-control
              v-model="form.cEnd"
              placeholder="任意时间点">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="持续时间：">
          <el-radio-group v-model="form.cKeep">
            <el-radio :label="1">一次</el-radio>
            <el-radio :label="0">每年</el-radio>
            <el-radio :label="-1">每月</el-radio>
            <el-radio :label="-3">每天</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="form.cText"
              maxlength="30"
              show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item v-if="insertVisible==true">
          <el-button @click="insertSubmit(form)">新增</el-button>
        </el-form-item>
        <el-form-item v-if="updateVisible==true">
          <el-button @click="update(form)">修改</el-button>
          <el-button @click="reset(form)">重置</el-button>
          <el-button @click="deleteCalendar(form)">删除</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>


    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="图表" name="first">
        <el-form inline style="background-color: rgba(255,255,255,0.7);padding: 0;margin: 0;width: 100%;height: 2.5em">
          <el-form-item>
            <el-date-picker
                v-model="myMonth"
                type="month"
                placeholder="选择月">
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button @click="getSummary">查询</el-button>
          </el-form-item>

          <el-form-item>
            <el-button @click="insert">新增日程</el-button>
          </el-form-item>
        </el-form>
        <!--    图表显示-->
        <el-row gutter="20">
          <el-col :span="12" style="width: 600px;padding: 0;margin: 0">
            <div id="myCalendar" style="height: 600px;width: 600px"></div>
          </el-col>
          <el-col style="width: 30%" :span="8">
            <div style="width: 100%">
              <el-card class="box-card" style="width: 100%">
                <template #header>
                  <div class="card-header">
                    <span>日程详情</span>
                    <!--                <el-button class="button" type="text">操作按钮</el-button>-->
                  </div>
                </template>
                <div v-for="list in dayCalendars">
                  <el-button @click="selectOne(list)" style="width: 100%;text-align: left">
                    <span >
                      {{list.cStart}}&#12288;&#12288;&#12288;
                    </span>
                    <span >
                      {{list.cName}}
                    </span>

                  </el-button>
                </div>
              </el-card>
            </div>
          </el-col>
        </el-row>


      </el-tab-pane>

      <!--    详情-->
      <el-tab-pane label="详情" name="second">
        <el-form inline style="background-color: rgba(255,255,255,0.7);padding: 0;margin: 0;width: 100%;height: 2.5em">
          <el-form-item>
            <el-date-picker
                v-model="myMonth"
                type="month"
                placeholder="选择月">
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button @click="selectMonth">查询</el-button>
          </el-form-item>

          <el-form-item>
            <el-button @click="insert">新增日程</el-button>
          </el-form-item>
        </el-form>

        <div v-for="list in calendars">
          <el-button @click="selectOne(list)" style="width: 60%;text-align: left">
            <span>
              {{getDate(list)}}&#12288;&#12288;&#12288;&#12288;
            </span>
            <span>
              {{list.cName}}
            </span>

          </el-button>
        </div>

      </el-tab-pane>



    </el-tabs>

    <div>
    </div>
  </div>

</template>

<script>
import * as echarts from 'echarts';
import moment from 'moment';
import { timestampToTime } from "./formatDate.js"
import {getMonthCalendar_0000,getOneCalendar_0000} from "../../api";
import {getSummaryCalendar_0000} from "../../api";
import {getDayCalendar_0000} from "../../api";
import {insert_15101,update_15201,delete_15301} from "../../api";

export default {
  name: "Calendar",
  data(){
    return{
      //限制只能选择当日以及之前的日期
      // disabledDate(time) {
      //   return time.getTime() > Date.now()
      // },
      shortcuts: [{
        text: '今天',
        value: new Date(),
      }, {
        text: '昨天',
        value: (() => {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24)
          return date
        })(),
      }, {
        text: '一周前',
        value: (() => {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
          return date
        })(),
      }],
      myCalendar:{
        cId:null,
        cName:null,
        cFlag:1,
        cDate:new Date(),
        cStart:0,
        cEnd:'23:59:59',
        cKeep:-1,
        cText:null,
        uId:null
      },
      form:{
        cId:null,
        cName:null,
        cFlag:1,
        cDate:new Date(),
        cStart:new Date(2021,6,2,0,0,0),
        cEnd:new Date(2021,6,2,23,59,59),
        cKeep:1,
        cText:null,
        uId:null
      },
      calendars:null,
      dayCalendars:null,
      activeName: 'first',
      myMonth:new Date(),
      showModel:2,
      showDialog:false,
      insertVisible:false,
      updateVisible:false
    }
  },
  mounted() {
    this.getSummary()
  },
  methods:{
    dateFormat(body) {
      const daterc = body
      if (daterc != null) {
        var str=daterc.toString()
        var yyyy=str.substr(0,4)
        var mm=str.substr(4,2)
        var dd=str.substr(6,2)
        var create=''+yyyy+'-'+mm+'-'+dd
        return new Date(create)
      }
    },
    deleteCalendar(form){
      const _this=this
      var body = {
        cId: form.cId,
        cName: form.cName,
        cFlag: form.cFlag,
        cDate: null,
        cStart: null,
        cEnd: null,
        cKeep: form.cKeep,
        cText: form.cText,
        uId: sessionStorage.getItem("uId")
      }

      //调用接口
      delete_15301(body).then(resp => {
        if (resp.code > 0) {
          this.$message({
            type: 'success',
            message: `删除成功`
          })
          _this.form = {
            cId: form.cId,
            cName: null,
            cFlag: 1,
            cDate: new Date(),
            cStart: new Date(2021, 6, 2, 0, 0, 0),
            cEnd: new Date(2021, 6, 2, 23, 59, 59),
            cKeep: 1,
            cText: null,
            uId: null
          }
          _this.showDialog=false
        } else {
          this.$message({
            type: 'error',
            message: '失败：' + resp.note
          })
        }
      }).catch(err=>{
        this.$message({
          type: 'error',
          message: '失败：' + err
        })
      })
    },
    update(form){
      const _this=this
      if (form.cName==null||form.cName.trim()==""){
        this.$message({
          type: 'error',
          message: `请完善日程名称`
        })
      }else {
        var body = {
          cId: form.cId,
          cName: form.cName,
          cFlag: form.cFlag,
          cDate: null,
          cStart: null,
          cEnd: null,
          cKeep: form.cKeep,
          cText: form.cText,
          uId: sessionStorage.getItem("uId")
        }
        var start = moment(new Date(2021, 6, 2, 0, 0, 0)).format('HH:mm:ss');
        var end = moment(new Date(2021, 6, 2, 23, 59, 59)).format('HH:mm:ss')
        if (form.cFlag == 2) {
          start = moment(form.cStart).format('HH:mm:ss');
          end = moment(form.cEnd).format('HH:mm:ss')
        } else if (form.cFlag == 3) {
          start = moment(form.cStart).format('HH:mm:ss');
          end = moment(form.cStart).format('HH:mm:ss')
        }
        // 格式化日期
        var uDate = moment(form.cDate).format('yyyyMMDD');

        body.cDate = parseInt(uDate)
        body.cStart = start
        body.cEnd = end

        //调用接口
        update_15201(body).then(resp => {
          if (resp.code > 0) {
            this.$message({
              type: 'success',
              message: `修改成功`
            })
            _this.form = {
              cId: form.cId,
              cName: null,
              cFlag: 1,
              cDate: new Date(),
              cStart: new Date(2021, 6, 2, 0, 0, 0),
              cEnd: new Date(2021, 6, 2, 23, 59, 59),
              cKeep: 1,
              cText: null,
              uId: null
            }
            _this.showDialog=false
          } else {
            this.$message({
              type: 'error',
              message: '失败：' + resp.note
            })
          }
        }).catch(err => {
          this.$message({
            type: 'error',
            message: '调用接口失败：' + err
          })
        })
      }
    },
    reset(body){
      this.getOne(body)
    },
    getDate(body){
      var str=body.cDate.toString()
      var yyyy=str.substr(0,4)
      var mm=str.substr(4,2)
      var dd=str.substr(6,2)
      var date=''+yyyy+'-'+mm+'-'+dd
      return date
    },
    selectOne(body){
      this.showDialog=true
      this.insertVisible=false
      this.updateVisible=true
      this.getOne(body)
    },
    insertSubmit(form){
      const _this=this
      if (form.cName==null||form.cName.trim()==""){
        this.$message({
          type: 'error',
          message: `请完善日程名称`
        })
      }else {
        var body={
          cId:null,
          cName:form.cName,
          cFlag:form.cFlag,
          cDate:null,
          cStart:null,
          cEnd:null,
          cKeep:form.cKeep,
          cText:form.cText,
          uId:sessionStorage.getItem("uId")
        }
        var start=moment(new Date(2021,6,2,0,0,0)).format('HH:mm:ss');
        var end=moment(new Date(2021,6,2,23,59,59)).format('HH:mm:ss')
        if(form.cFlag==2){
          start=moment(form.cStart).format('HH:mm:ss');
          end=moment(form.cEnd).format('HH:mm:ss')
        }else if(form.cFlag==3){
          start=moment(form.cStart).format('HH:mm:ss');
          end=moment(form.cStart).format('HH:mm:ss')
        }
        // 格式化日期
        var uDate=moment(form.cDate).format('yyyyMMDD');

        body.cDate=parseInt(uDate)
        body.cStart=start
        body.cEnd=end

        //调用接口
        insert_15101(body).then(resp=>{
          if(resp.code>0){
            this.$message({
              type: 'success',
              message: `新增成功`
            })
            _this.form={
              cId:null,
              cName:null,
              cFlag:1,
              cDate:new Date(),
              cStart:new Date(2021,6,2,0,0,0),
              cEnd:new Date(2021,6,2,23,59,59),
              cKeep:1,
              cText:null,
              uId:null
            }
          }else{
            this.$message({
              type: 'error',
              message: '失败：'+resp.note
            })
          }
        }).catch(err=>{
          this.$message({
            type: 'error',
            message: '调用接口失败：'+err
          })
        })

      }
    },
    getOne(body){
      const _this=this
      getOneCalendar_0000(body).then(resp=>{
        _this.form=resp
        _this.form.cDate=_this.dateFormat(_this.form.cDate)
        _this.form.cStart='2021-6-2 '+resp.cStart
        _this.form.cEnd='2021-6-2 '+resp.cEnd
        if(resp.cFlag=="全天"){
          _this.form.cFlag=1
        }
        if(resp.cFlag=="时间段"){
          _this.form.cFlag=2
        }
        if(resp.cFlag=="时刻"){
          _this.form.cFlag=3
        }
      }).catch(err=>{
        console.log(err)
      })
    },
    insert(){
      this.showDialog=true
      this.insertVisible=true
      this.updateVisible=false
      this.form={
        cId:null,
        cName:null,
        cFlag:1,
        cDate:new Date(),
        cStart:new Date(2021,6,2,0,0,0),
        cEnd:new Date(2021,6,2,23,59,59),
        cKeep:1,
        cText:null,
        uId:null
      }
    },
    selectMonth(){
      const _this=this;
      var uDate=moment(this.myMonth).format('yyyyMMDD');
      var body={
        uId:sessionStorage.getItem("uId"),
        cDate:parseInt(uDate)+31,
        cStart:moment(_this.myMonth).format('yyyy-MM-DD')
      }
      getMonthCalendar_0000(body).then(resp=>{
        _this.calendars=resp
      }).catch(err=>{
        console.log(err)
      })
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    setShowModel(record){
      this.showModel=record
      console.log(record)
    },
    getSummary(){
      const _this=this;
      var uDate=moment(this.myMonth).format('yyyyMMDD');
      var body={
        uId:sessionStorage.getItem("uId"),
        cDate:parseInt(uDate)+31,
        cStart:moment(this.myMonth).format('yyyy-MM-DD')
      }
      getSummaryCalendar_0000(body).then(resp=>{
        console.log(resp)
        _this.getCalendar(resp)
      }).catch(err=>{
        console.log(err)
      })
    },
    getCalendar(resp){
      var month=moment(this.myMonth).format('yyyy-MM');
      const _this=this
      var myChart = _this.$echarts.init(document.getElementById('myCalendar'));
      var dateList=[]
      for (var i = 0; i < resp.length; i++) {
        dateList.push([
          resp[i].name,
          resp[i].value,
        ])
      }

      function getVirtulData(year) {
        year = year || '2017';
        var date = +echarts.number.parseDate(year + '-01-01');
        var end = +echarts.number.parseDate((+year + 1) + '-01-01');
        var dayTime = 3600 * 24 * 1000;
        var data = [];
        for (var time = date; time < end; time += dayTime) {
          var items = [];
          var eventCount = 0
              // Math.round(Math.random() * pathes.length);
          for (var i = 0; i < eventCount; i++) {
            items.push(0)
                // Math.round(Math.random() * (pathes.length - 1)));
          }
          data.push([
            echarts.format.formatTime('yyyy-MM-dd', time),
            items.join('|')
          ]);
        }
        return data;
      }

      function renderItem(params, api) {
        var cellPoint = api.coord(api.value(0));
        var cellWidth = params.coordSys.cellWidth;
        var cellHeight = params.coordSys.cellHeight;

        var value = api.value(1);
        var events = value && value.split('|');

        if (isNaN(cellPoint[0]) || isNaN(cellPoint[1])) {
          return;
        }

        var group = {
          type: 'group',
          children: (layouts[events.length - 1] || []).map(function (itemLayout, index) {
            return {
              type: 'path',
              shape: {
                pathData: pathes[events[index]],
                x: -8,
                y: -8,
                width: 16,
                height: 16
              },
              position: [
                cellPoint[0] + echarts.number.linearMap(itemLayout[0], [-0.5, 0.5], [-cellWidth / 2, cellWidth / 2]),
                cellPoint[1] + echarts.number.linearMap(itemLayout[1], [-0.5, 0.5], [-cellHeight / 2 + 20, cellHeight / 2])
              ],
              style: api.style({
                fill: colors[events[index]]
              })
            };
          }) || []
        };

        group.children.push({
          type: 'text',
          style: {
            x: cellPoint[0],
            y: cellPoint[1] - cellHeight / 2 + 15,
            text: echarts.format.formatTime('dd', api.value(0)),
            fill: '#777',
            textFont: api.font({fontSize: 14})
          }
        });

        return group;
      }

      var heatmapData = [];
      var lunarData = [];
      for (var i = 0; i < dateList.length; i++) {
        heatmapData.push([
          dateList[i][0],
          dateList[i][1]*100
        ]);
        lunarData.push([
          dateList[i][0],
        ]);
      }


      var option = {
        tooltip: {
          formatter: function (params) {
            return '日程数量： ' + params.value[1]/100;
          }
        },
        visualMap: {
          show: false,
          min: 0,
          max: 300,
          calculable: true,
          seriesIndex: [2],
          orient: 'horizontal',
          left: 'center',
          bottom: 20,
          inRange: {
            color: ['#e0ffff', '#006edd'],
            opacity: 0.3
          },
          controller: {
            inRange: {
              opacity: 0.5
            }
          }
        },
        calendar: [{
          left: 'center',
          top: 'middle',
          cellSize: [70, 70],
          yearLabel: {show: false},
          orient: 'vertical',
          dayLabel: {
            firstDay: 1,
            nameMap: 'cn'
          },
          monthLabel: {
            show: false
          },
          range: month
        }],
        series: [{
          type: 'scatter',
          coordinateSystem: 'calendar',
          symbolSize: 1,
          label: {
            show: true,
            formatter: function (params) {
              var d = echarts.number.parseDate(params.value[0]);
              return d.getDate() + '\n\n'
                  // + params.value[2] + '\n\n';
            },
            color: '#000'
          },
          data: lunarData
        }, {
          type: 'scatter',
          coordinateSystem: 'calendar',
          symbolSize: 1,
          label: {
            show: true,
            formatter: function (params) {
              return '\n\n\n'
                  // + (params.value[3] || '');
            },
            fontSize: 14,
            fontWeight: 700,
            color: '#a00'
          },
          data: lunarData
        }, {
          name: '日程数',
          type: 'heatmap',
          coordinateSystem: 'calendar',
          data: heatmapData
        }]
      };
      myChart.on('click', function (params) {
        var value = params.value[0];
        // calander.setOption(option);

        // 这边写自己的业务逻辑，例如当天日期的日程安排
        console.log(value)
        _this.getDayCalendar(value)
      });
      myChart.setOption(option,true)
    },
    getDayCalendar(date){
      const _this=this
      var arr=date.split('-')
      var str=arr[0]+arr[1]+arr[2]
      var body={
        cDate:parseInt(str),
        uId:sessionStorage.getItem("uId"),
      }
      getDayCalendar_0000(body).then(resp=>{
        _this.dayCalendars=resp
      }).catch(err=>{
        console.log(err)
      })
    }
  }
}
</script>

<style scoped>
</style>